﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Rabbit.Utils;
using Rabbit.Model;
using Rabbit.BusinessLogicLayer;
using System.Collections.ObjectModel;

namespace MicroBlogClient.Pages
{
    enum OperationType
    {
        Status = 0,
        Following = 2,
        Follower = 1,
        None
    }
    /// <summary>
    /// Interaction logic for UserPage.xaml
    /// </summary>
    public partial class UserPage : PageBase
    {
        internal OperationType Operation;
        static OperationType operation= OperationType.None;
        public string UserName;
        static string previouseUserName;
        public bool IsLoadingByNickName = false;
 
        #region DependencyProperty
        public User CurrentUser
        {
            get { return (User)GetValue(CurrentUserProperty); }
            set { SetValue(CurrentUserProperty, value); }
        }

        // Using a DependencyProperty as the backing store for CurrentUser.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CurrentUserProperty =
            DependencyProperty.Register("CurrentUser", typeof(User), typeof(UserPage), new UIPropertyMetadata(null));
        #endregion

        UserFollowingListBL FollowingListBL = new UserFollowingListBL();
        UserFollowerListBL FollowerListBL = new UserFollowerListBL();
        UserStatusBL StatusBL = new UserStatusBL();

        public ObservableCollection<Status> StatusCollection { get; set; }
        public ObservableCollection<User> FollowerCollection { get; set; }
        public ObservableCollection<User> FollowingCollection { get; set; }
        public UserPage()
        {
            StatusCollection = new ObservableCollection<Status>();
            FollowerCollection = new ObservableCollection<User>();
            FollowingCollection = new ObservableCollection<User>();

            InitializeComponent();

            this.Loaded += new RoutedEventHandler(UserPage_Loaded);
            DataContext = this;
        }

        void UserPage_Loaded(object sender, RoutedEventArgs e)
        {
           DoWork(); 
        }

        public override void DoWork(object obj = null)
        {
            if (IsLoadingByNickName)
            {
                if (previouseUserName == UserName)
                {
                    return;
                }

                ShowProcessingMessage(string.Format("正在加载{0}的信息", UserName));
                previouseUserName = UserName;
                Action fetchingUserMessage = () =>
                {
                    try
                    {
                        User user = UserBL.GetUserInformationByScreenName(UserName);

                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            CurrentUser = user;
                            operation = Operation;
                            BeginInitializeMessage();
                        }));
                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogError(ex);
                        ShowFailedMessage(string.Format("获取用户: {0}信息失败", UserName));
                    }
                };
                fetchingUserMessage.BeginInvoke(null, null);
            }
            else
            {
                if (CurrentUser == null)
                {
                    CurrentUser = UserBL.CurrentUser;
                }
                if (Operation != operation || previouseUserName != CurrentUser.ScreenName)
                {
                    ShowProcessingMessage(string.Format("正在加载{0}的信息", CurrentUser.ScreenName));

                    previouseUserName = CurrentUser.ScreenName;
                    operation = Operation;
                    BeginInitializeMessage();
                }
            }
        }
 
        protected override void NotifyMainWindowNewMessageCountChanged(int messageCount)
        {
            throw new NotImplementedException();
        }

        public override void BeginInitializeMessage()
        {
            tcMain.SelectedIndex = (int)Operation;
            long userID = CurrentUser.Id;

            Action fetchingNewMessage = () =>
                {
                    FollowerListBL.UserID = userID;
                    FollowingListBL.UserID = userID;
                    StatusBL.UserID = userID;

                    try
                    {
                        List<User> followers = FollowerListBL.GetFirstPageMessage();
                        List<User> followings = FollowingListBL.GetFirstPageMessage();
                        List<Status> statuses = StatusBL.GetFirstPageMessage();

                        this.Dispatcher.BeginInvoke(new Action(()=>
                                {
                                    FollowerCollection.Clear();
                                    FollowingCollection.Clear();
                                    StatusCollection.Clear();

                                    followers.ForEach(f => FollowerCollection.Add(f));
                                    followings.ForEach(f => FollowingCollection.Add(f));
                                    statuses.ForEach(s=>StatusCollection.Add(s));
                                }
                            )
                        );
                        base.HideMessage();
                        //ShowSuccessfulMessage("加载成功");
                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogError(ex);
                        ShowSuccessfulMessage("加载失败");
                    }
                };
            fetchingNewMessage.BeginInvoke(null, null);
        }

        public override void pager_OnFirstPageClick(object sender, RoutedEventArgs e)
        {
            ShowProcessingMessage("正在加载...");
            UCPager pager = sender as UCPager;

            string oper = pager.Tag.ToString();
            Action fetching = () =>
            {
                try
                {
                    bool canNextPageClick = false;
                    if (oper == "status")
                    {
                        List<Status> fetchedMessage = StatusBL.GetFirstPageMessage();
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            StatusCollection.Clear();
                            fetchedMessage.ForEach(c => StatusCollection.Add(c));
                            canNextPageClick = StatusBL.CanGetNextPage;
                            if (StatusCollection.Count > 0)
                            {
                                lstStatus.ScrollIntoView(StatusCollection[0]);
                            }
                        }));
                    }
                    else if (oper == "following")
                    {
                        List<User> fetchedMessage = FollowingListBL.GetFirstPageMessage();
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            FollowingCollection.Clear();
                            fetchedMessage.ForEach(c => FollowingCollection.Add(c));
                            canNextPageClick = FollowingListBL.CanGetNextPage;
                            if (FollowingCollection.Count > 0)
                            {
                                lstFollowing.ScrollIntoView(FollowingCollection[0]);
                            }
                        }));
                    }
                    else if (oper == "follower")
                    {
                        List<User> fetchedMessage = FollowerListBL.GetFirstPageMessage();
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            FollowerCollection.Clear();
                            fetchedMessage.ForEach(c => FollowerCollection.Add(c));
                            canNextPageClick = FollowerListBL.CanGetNextPage;
                            if (FollowerCollection.Count > 0)
                            {
                                lstFollower.ScrollIntoView(FollowerCollection[0]);
                            }
                        }));
                    }
                    this.Dispatcher.BeginInvoke(new Action(() =>
                      {
                          pager.CanPreviousePageClick = false;
                          pager.CanNextPageClick = canNextPageClick;
                      }
               ));
                    base.HideMessage();
                    //ShowSuccessfulMessage("加载完成");
                }
                catch (Exception ex)
                {
                    ShowFailedMessage("获取失败:" + ex.Message);
                }
            };

            fetching.BeginInvoke(null, null);
        }

        public override void pager_OnPreviousePage(object sender, RoutedEventArgs e)
        {
            ShowProcessingMessage("正在加载...");
            UCPager pager = sender as UCPager;

            string oper = pager.Tag.ToString();
            Action fetching = () =>
            {
                try
                {
                    bool canNextPageClick = false;
                    bool canPreviouseClick = false;
                    if (oper == "status")
                    {
                        List<Status> fetchedMessage = StatusBL.GetPreviousePageMessage();
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            StatusCollection.Clear();
                            fetchedMessage.ForEach(c => StatusCollection.Add(c));
                            canPreviouseClick = StatusBL.CanGetPreviousePage;
                            canNextPageClick = StatusBL.CanGetNextPage;
                            if (StatusCollection.Count > 0)
                            {
                                lstStatus.ScrollIntoView(StatusCollection[0]);
                            }
                        }));
                    }
                    else if (oper == "following")
                    {
                        List<User> fetchedMessage = FollowingListBL.GetPreviousePageMessage();
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            FollowingCollection.Clear();
                            fetchedMessage.ForEach(c => FollowingCollection.Add(c));
                            canNextPageClick = FollowingListBL.CanGetNextPage;
                            canPreviouseClick = FollowingListBL.CanGetPreviousePage;
                            if (FollowingCollection.Count > 0)
                            {
                                lstFollowing.ScrollIntoView(FollowingCollection[0]);
                            }
                        }));
                    }
                    else if (oper == "follower")
                    {
                        List<User> fetchedMessage = FollowerListBL.GetPreviousePageMessage();
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            FollowerCollection.Clear();
                            fetchedMessage.ForEach(c => FollowerCollection.Add(c));
                            canNextPageClick = FollowerListBL.CanGetNextPage;
                            canPreviouseClick = FollowerListBL.CanGetPreviousePage;

                            if (FollowerCollection.Count > 0)
                            {
                                lstFollower.ScrollIntoView(FollowerCollection[0]);
                            }
                        }));
                    }
                    this.Dispatcher.BeginInvoke(new Action(() =>
                       {
                           pager.CanPreviousePageClick = canPreviouseClick;
                           pager.CanNextPageClick = canNextPageClick;
                       }));
                    base.HideMessage(); 
                }
                catch (Exception ex)
                {
                    ShowFailedMessage("获取失败:" + ex.Message);
                }
            };

            fetching.BeginInvoke(null, null);
        }

        public override void pager_OnNextPageClick(object sender, RoutedEventArgs e)
        {
            ShowProcessingMessage("正在加载...");
            UCPager pager = sender as UCPager;

            string oper = pager.Tag.ToString();

            Action fetching = () =>
            {
                try
                {
                    bool canNextPageClick = false;
                    if (oper == "status")
                    {
                        List<Status> fetchedMessage = StatusBL.GetNextPageMessage();
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            StatusCollection.Clear();
                            fetchedMessage.ForEach(c => StatusCollection.Add(c));
                            canNextPageClick = StatusBL.CanGetNextPage;
                            if (StatusCollection.Count > 0)
                            {
                                lstStatus.ScrollIntoView(StatusCollection[0]);
                            }
                        }));
                    }
                    else if (oper == "following")
                    {
                        List<User> fetchedMessage = FollowingListBL.GetNextPageMessage();
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            FollowingCollection.Clear();
                            fetchedMessage.ForEach(c => FollowingCollection.Add(c));
                            canNextPageClick = FollowingListBL.CanGetNextPage;
                            if (FollowingCollection.Count > 0)
                            {
                                lstFollowing.ScrollIntoView(FollowingCollection[0]);
                            }
                        }));
                    }
                    else if (oper == "follower")
                    {
                        List<User> fetchedMessage = FollowerListBL.GetNextPageMessage();
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            FollowerCollection.Clear();
                            fetchedMessage.ForEach(c => FollowerCollection.Add(c));
                            canNextPageClick = FollowerListBL.CanGetNextPage;
                            if (FollowerCollection.Count > 0)
                            {
                                lstFollower.ScrollIntoView(FollowerCollection[0]);
                            }
                        }));
                    }
                    this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            pager.CanPreviousePageClick = true;
                            pager.CanNextPageClick = canNextPageClick;
                        }));
                    base.HideMessage();
                }
                catch (Exception ex)
                {
                    ShowFailedMessage("获取失败:" + ex.Message);
                }
            };

            fetching.BeginInvoke(null, null);
        }

        private void MakeFriends_Click(object sender, RoutedEventArgs e)
        {
            ShowProcessingMessage("正在添加关注");
            long userID = long.Parse((sender as Hyperlink).CommandParameter.ToString());
            Action makeFriends = () =>
            {
                try
                {
                    User result = UserBL.CreateFriendship(userID);
                    this.Dispatcher.BeginInvoke(new Action(() => {
                        (Common.GetListBoxItemFromChild((sender as Hyperlink).Parent as DependencyObject).Content as User).Following = true;
                    }));
                    ShowSuccessfulMessage("关注成功");
                }
                catch (Exception)
                {
                    ShowFailedMessage("关注失败,您已经关注过此人");
                }
            };
            makeFriends.BeginInvoke(null, null);
        }

        public override void StopFetchingMessage()
        {
            StatusCollection.Clear();
            FollowerCollection.Clear();
            FollowingCollection.Clear();
        }
    }
}
